<?php

namespace app\shop\controller\api;

use app\ApiController;
use app\member\model\UsersModel;
use app\shop\model\CartModel;
use app\shop\model\GoodsModel;
use app\shop\model\PrizeWinModel;
use app\shop\model\ShopPageTheme;
use app\weixin\model\MiniModel;
use think\Db;
use think\facade\Env;
use think\facade\Request;

/*------------------------------------------------------ */
//-- 商品相关API
/*------------------------------------------------------ */

class Goods extends ApiController
{
    /*------------------------------------------------------ */
    //-- 优先执行
    /*------------------------------------------------------ */
    public function initialize()
    {
        parent::initialize();
        $this->Model = new GoodsModel();
    }
    /*------------------------------------------------------ */
    //-- 获取商品列表
    /*------------------------------------------------------ */
    public function getList()
    {
        $this->Model->autoSale();//自动上下架处理
        $where[] = ['is_delete', '=', 0];
        $where[] = ['is_alone_sale', '=', 1];
        $where[] = ['isputaway', '=', 1];

        $search['keyword'] = input('keyword', '', 'trim');
        if (empty($search['keyword']) == false) {
            $where['and'][] = "( goods_name like '%" . $search['keyword'] . "%')  OR ( keywords like '%" . $search['keyword'] . "%')";
        }
        $search['supplyer_id'] = input('supplyer_id', 0, 'intval');
        if ($search['supplyer_id'] > 0) {
            $where[] = ['supplyer_id', '=', $search['supplyer_id']];
        }

        $search['cateId'] = input('cateId', 0, 'intval');
        if ($search['cateId'] > 0) {
            $classList = $this->Model->getClassList();
            $where[] = ['cid', 'in', $classList[$search['cateId']]['children']];
        }
        $search['brand_id'] = input('brand_id', 0, 'intval');
        if ($search['brand_id'] > 0) {
            $where[] = ['brand_id', '=', $search['brand_id']];
        }

        $search['ids'] = input('ids', '', 'trim');
        if (empty($search['ids']) == false) {
            $where[] = ['goods_id', 'in', $search['ids']];
        }
//        $where[] = ['goods_type', '=', 0];
//        if($this->userInfo['user_id']){
//            if($this->userInfo['role_id'] !== 0 && $this->userInfo['role_id'] !== 3){
//                $where[] = ['goods_type', 'in', [0,4,6]];
//            }else{
//                $where[] = ['goods_type', 'in', [4,6]];
//            }
//        }else{
//            $where[] = ['goods_type', 'in', [4,6]];
//        }

        $sqlOrder = input('order', '', 'trim');
        $sort_by = strtoupper(input('sort', 'DESC', 'trim'));
        if (in_array(strtoupper($sort_by), array('DESC', 'ASC')) == false) {
            $sort_by = 'DESC';
        }
        switch ($sqlOrder) {
            case 'new':
                $this->sqlOrder = "is_new DESC,goods_id DESC";
                break;
            case 'sales':
                $this->sqlOrder = "virtual_sale $sort_by,goods_id DESC";
                break;
            case 'price':
                $this->sqlOrder = "shop_price $sort_by,goods_id DESC";
                break;
            default:
                $this->sqlOrder = "sort_order $sort_by,virtual_sale $sort_by,virtual_collect $sort_by,is_best $sort_by,goods_id DESC";
                break;
        }
        $data = $this->getPageList($this->Model, $where, 'goods_id', 10);
        $show_stock_num = settings('shop_goods_show_stock_num');
        $show_market_price = settings('shop_goods_show_market_price');
        foreach ($data['list'] as $key => $goods) {
            $goods = $this->Model->info($goods['goods_id']);
            $_goods['goods_id'] = $goods['goods_id'];
            $_goods['goods_name'] = $goods['goods_name'];
            $_goods['short_name'] = $goods['short_name'];
            if (empty($_goods['short_name'])) {
                $_goods['short_name'] = $goods['goods_name'];
            }
            $_goods['goods_name'] = $goods['goods_name'];
            $_goods['is_spec'] = $goods['is_spec'];
            $_goods['exp_price'] = $goods['exp_price'];
            $_goods['sale_price'] = $goods['sale_price'];
            $_goods['now_price'] = $goods['sale_price'];
            $_goods['market_price'] = $goods['market_price'];
            $_goods['sale_count'] = $goods['sale_count'];
            $_goods['collect_count'] = $goods['collect_count'];
            $_goods['goods_thumb'] = $goods['goods_thumb'];
            $_goods['goods_number'] = $goods['goods_number'];
            $_goods['show_stock_num'] = $show_stock_num;
            $_goods['show_market_price'] = $show_market_price;
            $data['list'][$key] = $_goods;
        }
        return $this->success($data);
    }
    public function getTeamLevelIds($user_id,$return_arr){
        $child_list = Db::name('users_bind_superior')->where('find_in_set('.$user_id.',superior)')->column('user_id');
        return $child_list;
    }
    public function calculateAward($num,$goods)
    {
        $setting = json_decode($goods['lc_award_value'],true);
        $config = [];
        $award = 0;
//        if($setting['team']){
//            $setting['team'] = json_decode($setting['team'],true);
        $config = $setting;
        $config = array_reverse($config);
        foreach ($config as $value){
            if($value['min_order_num'] <= $num && $num <= $value['max_order_num']){
                $award = $value['award_amount'];
                break;
            }
        }
//        }
        return $award;
    }
    public function getPrice($vip_discount, $price,$goods)
    {
        if (!empty($this->userInfo['role_id']) && !empty($vip_discount)) {
            $vip_discount = json_decode($vip_discount, true);
            if (!empty($vip_discount[$this->userInfo['role_id']]['num'])) {
                $price = bcmul($price, ($vip_discount[$this->userInfo['role_id']]['num'] / 10));
            }
//            if($this->userInfo['role_id'] == 14){
//                $goods_ids = Db::name('shop_goods')->where(['is_lc' => 1])->column('goods_id');
//                $child = $this->getTeamLevelIds($this->userInfo['user_id'],[]);
//                $child[] = $this->userInfo['user_id'];
//                $order_num = Db::name('shop_order_info')->alias('o')->join('shop_order_goods og','og.order_id = o.order_id')
//                    ->where('og.goods_id','in',$goods_ids)
//                    ->where('o.pay_time', '>', $this->userInfo['lc_time'])
//                    ->where('o.user_id','in',$child)->sum('og.goods_number');
//                $award = $this->calculateAward($order_num,$goods);
//                return $price - $award;
//            }
        }
        return $price;
    }
    /*------------------------------------------------------ */
    //-- 获取商品信息
    /*------------------------------------------------------ */
    public function getGoodsInfo()
    {
        $goods_id = input('goods_id', 0, 'intval');
        if ($goods_id < 1) {
            return $this->error('请传递商品ID.');
        }
        $data = $this->Model->info($goods_id);
        $data['show_sale_num'] = settings('shop_goods_show_sale_num');
        $data['show_collect_num'] = settings('shop_goods_show_collect_num');
        $data['show_market_price'] = settings('shop_goods_show_market_price');
        $data['show_stock_num'] = settings('shop_goods_show_stock_num');
        $data['shop_goods_comment'] = settings('shop_goods_comment');
        if (empty($data)) {
            return $this->error('没有找到相关商品.');
        }
        $data['is_collect'] = 0;
        if (empty($this->userInfo['user_id']) == false) {//已登陆，查询用户是否有收藏此商品
            $where['goods_id'] = $goods_id;
            $where['user_id'] = $this->userInfo['user_id'];
            $where['status'] = 1;
            $data['is_collect'] = (new \app\shop\model\GoodsCollectModel)->where($where)->count();
        }
        //商家自定义首页ID
        if($data['supplyer_id']){
            $data['store_index_id'] = 0;
            $data['store_index_id'] = (new ShopPageTheme())->where(['supplyer_id' => $data['supplyer_id'],'is_store_index' => 1])->value('st_id');
            if($data['store_index_id']){
                $data['store_page'] = '/pages/shop/index/diypage?pageid='.$data['store_index_id'];
            }else{
                $data['store_page'] = '/pages/shop/store/index?id='.$data['supplyer_id'];
            }

        }
        return $this->success($data);
    }



    /*------------------------------------------------------ */
    //-- 获取商品品牌列表
    /*------------------------------------------------------ */
    public function getBrandList()
    {
        $cid = input('cid', 0, 'intval');
        $return['list'] = $this->Model->getBrandList($cid);
        $return['code'] = 1;
        return $this->ajaxReturn($return);
    }



    /*------------------------------------------------------ */
    //-- 添加/取消收藏商品
    /*------------------------------------------------------ */
    public function collect()
    {
        $this->checkLogin();//验证登陆
        $goods_id = input('goods_id', 0, 'intval');
        if ($goods_id < 1) return $this->error('传参失败.');
        $GoodsCollectModel = new \app\shop\model\GoodsCollectModel();
        $where['goods_id'] = $goods_id;
        $where['user_id'] = $this->userInfo['user_id'];
        $collect = $GoodsCollectModel->where($where)->find();
        if (empty($collect) == false) {//存在,更新状态
            $upData['status'] = $collect['status'] == 1 ? 0 : 1;
            $upData['update_time'] = time();
            $res = $GoodsCollectModel->where($where)->update($upData);
        } else {
            $inData['status'] = 1;
            $inData['goods_id'] = $goods_id;
            $inData['user_id'] = $this->userInfo['user_id'];
            $inData['add_time'] = time();
            $inData['update_time'] = time();
            $res = $GoodsCollectModel->save($inData);
        }
        if ($res < 1) return $this->error('收藏商品失败.');
        return $this->success();
    }

    /*------------------------------------------------------ */
    //-- 获取商品收藏列表
    /*------------------------------------------------------ */
    public function getCollectlist()
    {
        $this->checkLogin();//验证登陆
        $GoodsCollectModel = new \app\shop\model\GoodsCollectModel();
        $where['user_id'] = $this->userInfo['user_id'];
        $where['status'] = 1;
        $rows = $GoodsCollectModel->where($where)->order('update_time DESC')->select();
        foreach ($rows as $row) {
            $goods = $this->Model->info($row['goods_id']);
            if ($goods['is_delete'] == 1) {
                continue;
            }
            $_goods['goods_id'] = $goods['goods_id'];
            $_goods['goods_name'] = $goods['goods_name'];
            $_goods['short_name'] = $goods['short_name'];
            $_goods['is_spec'] = $goods['is_spec'];
            $_goods['exp_price'] = $goods['exp_price'];
            $_goods['sale_price'] = $goods['sale_price'];
            $_goods['market_price'] = $goods['market_price'];
            $_goods['sale_count'] = $goods['sale_count'];
            $_goods['collect_count'] = $goods['collect_count'];
            $_goods['goods_thumb'] = $goods['goods_thumb'];
            $_goods['is_promote'] = $goods['is_promote'];
            $return['list'][] = $_goods;
            $return['count'] += 1;
        }
        return $this->success($return);
    }
    /*------------------------------------------------------ */
    //-- 获取商品详情
    /*------------------------------------------------------ */
    public function info()
    {
        $goods_id = input('id', 0, 'intval');
        if ($goods_id < 1) return $this->error('传参错误.');
        $goods = $this->Model->info($goods_id);
        $list['title'] = $goods['goods_name'];

        $web_path = config('config.host_path');
        $goods['m_goods_desc'] = preg_replace('/<img src=\"/', '<img style="width:100%;height:auto;" src="' . $web_path, $goods['m_goods_desc']);
        $list['goods'] = $goods;
        $list['imgsList'] = $this->Model->getImgsList($goods_id);
        $list['skuImgs'] = $this->Model->getImgsList($goods_id, true, true);
        $list['isCollect'] = $this->Model->isCollect($goods_id, $this->userInfo['user_id']);
        //获取sku图片

        //获取购物车信息
        $CartModel = new CartModel();
        $list['cartInfo'] = $CartModel->getCartInfo();

        $return['code'] = 1;
        $return['list'] = $list;
        return $this->ajaxReturn($return);
    }
    /*------------------------------------------------------ */
    //-- 获取搜索词，热搜之类的
    /*------------------------------------------------------ */
    public function get_keyword()
    {
        $return['default_keyword'] = settings('shop_index_search_text');
        $return['searchKeys'] = $this->Model->searchKeys();
        $return['hot_search'] = explode(' ', settings('hot_search'));
        $return['code'] = 1;
        return $this->ajaxReturn($return);
    }

    /*------------------------------------------------------ */
    //-- 检查商品活动
    /*------------------------------------------------------ */
    public function checkActivity()
    {
        if (class_exists('app\favour\model\FavourGoodsModel') == false) {
            return $this->success();
        }
        $goods_id = input('goods_id', 0, 'intval');
        $sku_id = input('sku_id', 0, 'intval');
        $goods = (new \app\favour\model\FavourGoodsModel)->checkIsFavour($goods_id, $sku_id);
        return $this->success($goods);
    }

    /*------------------------------------------------------ */
    //-- 商品分享页二维码
    /*------------------------------------------------------ */
    public function getShareImg()
    {
        $isnew = input('isnew', 0, 'intval');
        $is_wxmp = input('is_wxmp', 0, 'intval');
        $goods_id = input('goods_id', 0, 'intval');
        $file_name = $goods_id . '_' . $this->userInfo['user_id'] . '_' . $is_wxmp . '.jpg';
        $file_path = config('config._upload_') . 'goods_code/';
        if ($isnew == 0 && file_exists($file_path . $file_name) == true) {
            $res['img'] = trim($file_path . $file_name, '.');
            return $this->success($res);
        }
        makeDir($file_path);
        $goods = $this->Model->info($goods_id);

        $settings = settings();
        $UsersModel = new UsersModel();
        $data['share_goods_bg'] = $settings['share_goods_bg'];
        $data['share_avatar'] = $UsersModel->getHeadImg($this->userInfo['headimgurl']);
        $data['share_avatar']= Env::get('root_path') . 'public'.ltrim($data['share_avatar'],'.');
        $data['share_nick_name'] = $this->userInfo['nick_name'];
        $data['share_qrcode'] = $is_wxmp == 0 ? $UsersModel->getMyQrCode($goods_id) : $UsersModel->getUserMiniQrcode($goods_id);

        $data['share_goods_name'] = $goods['goods_name'];
        $data['share_goods_price'] = '￥' . $goods['shop_price'];
        $data['share_goods_img'] = '.' . $goods['goods_img'];
        $data['share_goods_xy'] = $settings['share_goods_xy'];
        $data['share_goods_wh'] = $settings['share_goods_wh'];
        $data['share_goods_name_xy'] = $settings['share_goods_name_xy'];
        $data['share_goods_nickname_center'] = $settings['share_goods_nickname_center'];
        $data['share_goods_name_color'] = $settings['share_goods_name_color'];
        $data['share_goods_name_size'] = $settings['share_goods_name_size'];
        $data['share_goods_name_br'] = $settings['share_goods_name_br'];
        $data['share_goods_price_xy'] = $settings['share_goods_price_xy'];
        $data['share_goods_price_color'] = $settings['share_goods_price_color'];
        $data['share_goods_price_size'] = $settings['share_goods_price_size'];

        $data['share_goods_avatar_xy'] = $settings['share_goods_avatar_xy'];
        $data['share_goods_avatar_width'] = $settings['share_goods_avatar_width'];
        $data['share_goods_avatar_shape'] = $settings['share_goods_avatar_shape'];
        $data['share_goods_nickname_xy'] = $settings['share_goods_nickname_xy'];
        $data['share_goods_nickname_color'] = $settings['share_goods_nickname_color'];
        $data['share_goods_nickname_size'] = $settings['share_goods_nickname_size'];
        $data['share_goods_qrcode_xy'] = $settings['share_goods_qrcode_xy'];
        $data['share_goods_qrcode_width'] = $settings['share_goods_qrcode_width'];
        $MergeImg = new \lib\MergeImg();
        $MergeImg->shareGoodsImg($data, $file_path . $file_name);
        $res['img'] = trim($file_path . $file_name, '.') . '?v=' . time();
        $res['share_url'] = config('config.host_path') . '/pages/shop/goods/info?goods_id=' . $goods_id . '&share_token=' . $this->userInfo['token'];
        return $this->success($res);
    }


    /*------------------------------------------------------ */
    //-- 获取商品分类
    /*------------------------------------------------------ */
    public function getCateList()
    {
        $data['list'] = returnRecArr($this->Model->getClassList(false));
        return $this->success($data);
    }

    /*
     * 获取奖品
     */
    public function getPrizegoods(){
        //$prizeObj = new PrizeGoods();

        //获取抽奖设置 计算用户获得抽奖次数  琳凯start
        $prizeSetres = Db::table('shop_prize_set')->where('id',1)->find();
        //是否开启
        $isopen = $prizeSetres['isopen'];
        $userid = $this->userInfo['user_id'];
        //设置的推荐几个下级
        //$tuijieNum = $prizeSetres['tjnum'];
        $rolefensinum = $this->userInfo['rolefensi'];   //被记录粉丝数
        $rolemembernum = $this->userInfo['rolemember']; //被记录会员数
        $roledailinum = $this->userInfo['roledaili'];   //被记录代理数
        $rolejinlinum = $this->userInfo['rolejinli'];   //被记录经理数

        //查当前用户下面级别数
        $userfensinum = Db::table('users')->where([['role_id','=',0],['pid','=',$this->userInfo['pid']]])->count();  //当前用户下面的粉丝数
        $usermembernum = Db::table('users')->where([['role_id','=',3],['pid','=',$this->userInfo['pid']]])->count();  //当前用户下面的会员数
        $userdailinum = Db::table('users')->where([['role_id','=',1],['pid','=',$this->userInfo['pid']]])->count();  //当前用户下面的代理数
        $userjinglinum = Db::table('users')->where([['role_id','=',2],['pid','=',$this->userInfo['pid']]])->count();  //当前用户下面的经理数

        //dump($this->userInfo['rolefensi']);
        if($isopen == 1){
            //查设置的自己身份
            $userstjrole_id = $prizeSetres['tjrole_id'];
            //查设置的被推荐身份
            $usersbtjrole_id = $prizeSetres['btjrole_id'];

                if($usersbtjrole_id == 0){

                    //开始算法
                    $newfensinum = abs($userfensinum-$rolefensinum);  //新增的粉丝数
                    if($newfensinum>=1){
                        //计算新增次数 加到用户抽奖次数
                        $jisuantimes = intval($newfensinum / $prizeSetres['tjnum']);  //取整数
                        //$yushu = abs($newfensinum % $prizeSetres['tjnum']);  //求余数
                        if($jisuantimes>=1){

                            //更新被记录的下级个数
                            $newuserfensinum = $rolefensinum+(abs($prizeSetres['tjnum']*$jisuantimes));
                            $updataUserfensires = Db::table('users')->where('user_id',$userid)->update(['rolefensi'=>$newuserfensinum]);
                            if($updataUserfensires || $updataUserfensires>0){
                                $newtimes = abs( $jisuantimes+$this->userInfo['prize_num']);  // 更新后新次数
                                //更新当前用户次数
                                Db::table('users')->where('user_id',$userid)->update(['prize_num'=>$newtimes]);
                            }

                        }
                    }
                    //结束算法
                }else if($usersbtjrole_id == 3){
                    //开始算法
                    $newfensinum = abs($usermembernum-$rolemembernum);  //新增的代理数
                    if($newfensinum>=1){
                        //计算新增次数 加到用户抽奖次数
                        $jisuantimes = intval($newfensinum / $prizeSetres['tjnum']);  //取整数
                        //$yushu = abs($newfensinum % $prizeSetres['tjnum']);  //求余数
                        if($jisuantimes>=1){

                            //更新被记录的下级个数
                            $newuserfensinum = $rolemembernum+(abs($prizeSetres['tjnum']*$jisuantimes));
                            $updataUserfensires = Db::table('users')->where('user_id',$userid)->update(['rolefensi'=>$newuserfensinum]);
                            if($updataUserfensires || $updataUserfensires>0){
                                $newtimes = abs( $jisuantimes+$this->userInfo['prize_num']);  // 更新后新次数
                                //更新当前用户次数
                                Db::table('users')->where('user_id',$userid)->update(['prize_num'=>$newtimes]);
                            }

                        }
                    }
                    //结束算法
                }else if($usersbtjrole_id == 1){
                    //开始算法
                    $newfensinum = abs($userjinglinum-$roledailinum);  //新增的会员数
                    if($newfensinum>=1){
                        //计算新增次数 加到用户抽奖次数
                        $jisuantimes = intval($newfensinum / $prizeSetres['tjnum']);  //取整数
                        //$yushu = abs($newfensinum % $prizeSetres['tjnum']);  //求余数
                        if($jisuantimes>=1){

                            //更新被记录的下级个数
                            $newuserfensinum = $roledailinum+(abs($prizeSetres['tjnum']*$jisuantimes));
                            $updataUserfensires = Db::table('users')->where('user_id',$userid)->update(['rolefensi'=>$newuserfensinum]);
                            if($updataUserfensires || $updataUserfensires>0){
                                $newtimes = abs( $jisuantimes+$this->userInfo['prize_num']);  // 更新后新次数
                                //更新当前用户次数
                                Db::table('users')->where('user_id',$userid)->update(['prize_num'=>$newtimes]);
                            }

                        }
                    }
                    //结束算法
                }else if($usersbtjrole_id == 2){
                    //开始算法
                    $newfensinum = abs($userdailinum-$rolejinlinum);  //新增的经理数
                    if($newfensinum>=1){
                        //计算新增次数 加到用户抽奖次数
                        $jisuantimes = intval($newfensinum / $prizeSetres['tjnum']);  //取整数
                        //$yushu = abs($newfensinum % $prizeSetres['tjnum']);  //求余数
                        if($jisuantimes>=1){

                            //更新被记录的下级个数
                            $newuserfensinum = $rolejinlinum+(abs($prizeSetres['tjnum']*$jisuantimes));
                            $updataUserfensires = Db::table('users')->where('user_id',$userid)->update(['rolefensi'=>$newuserfensinum]);
                            if($updataUserfensires || $updataUserfensires>0){
                                $newtimes = abs( $jisuantimes+$this->userInfo['prize_num']);  // 更新后新次数
                                //更新当前用户次数
                                Db::table('users')->where('user_id',$userid)->update(['prize_num'=>$newtimes]);
                            }

                        }
                    }
                    //结束算法
                }

        }
        //琳凯end


        $where[] = ['is_delete','=',0];
        $where[] = ['status','=',1];
        //$where[] = ['num','>=',1];
        $res = Db::table('shop_prize_goods')->where($where)->select();
        $hostname = Request::domain();
        foreach ($res as $k=>$v){
            $res[$k]['photo'] = $hostname.$v['photo'];
        }


        //dump($res);
        return $this->success($res);
    }
    /*
     * 获取用户抽奖次数
     */
    public function getUserPrizenum(){
        $userId = $this->userInfo['user_id'];
        $userObj = Db::table('users')->where('user_id','=',$userId)->find();
        //dump($userObj['prize_num']);
        $prizenum = $userObj['prize_num'];
        if($prizenum <= 0){
            $prizenum = 0;
        }



        return $this->success('200','',$prizenum);
    }
    /*
     * 点击一次减少用户抽奖次数  无用
     */
    public function subUserPrizenum(){
        $userId = $this->userInfo['user_id'];
        $userObj = Db::table('users')->where('user_id','=',$userId)->find();

        $prizenum = $userObj['prize_num'];
        if($prizenum <= 0){
            $this->error('您的抽奖次数已经用完','',$prizenum);
        }
        $prizenum = $prizenum-1;
        $res = Db::table('users')->where('user_id',$userId)->update(['prize_num'=>$prizenum]);
        if(!$res){
            $this->error('200','',$prizenum);
        }

        return $this->success('200','',$prizenum);
    }

    /*
     * 抽中奖品 减少数量 无用
     */
    public function subPrizeGoodsnum(){
        $prizegoodsid = input('id','','intval');
        $userId = $this->userInfo['user_id'];


        $prizegoodsObj = Db::table('shop_prize_goods')->where('id','=',$prizegoodsid)->find();

        if($prizegoodsObj['num'] <= 0){
            $this->error('该奖品已经抽完了','','0');
        }

        $userObj = Db::table('users')->where('user_id','=',$userId)->find();

        if($userObj['prize_num'] <= 0){
            $this->error('您的抽奖次数已经用完','',$prizenum);
        }
        $prizenum = $userObj['prize_num']-1;
        $res = Db::table('users')->where('user_id',$userId)->update(['prize_num'=>$prizenum]);

        $goodsnum = $prizegoodsObj['num']-1;
        $goodsres = Db::table('shop_prize_goods')->where('id',$prizegoodsid)->update(['num'=>$goodsnum]);

        $prizegoodsres = Db::table('shop_prize_goods')->where('id','=',$prizegoodsid)->find();
        $numres = Db::table('users')->where('user_id','=',$userId)->find();
        $data['times'] = $numres['prize_num'];
        $data['goods'] = $prizegoodsres;
        if($res && $goodsres){
            $this->error('OK','',$data);
        }

    }


    /*
     * 抽中奖品 减少数量
     */
    public function getWinnerGoods()
    {
        $userId = $this->userInfo['user_id'];

        //缓存锁
        $cacheKey = 'prize_goods_userId_' . $userId;
        cache($cacheKey, null);
        if (cache($cacheKey)) {
            $this->error('正在抽奖中');
        }
        cache($cacheKey, 1, 300);

        try {
            //获取奖品
            $where[] = ['is_delete', '=', 0];
            $where[] = ['status', '=', 1];
            $where[] = ['num', '>', 0];
            $goods = Db::table('shop_prize_goods')->where($where)->select();
            if (empty($goods)) {
                throw new \Exception('奖品已抽完');
            }

            $userObj = Db::table('users')->where('user_id', '=', $userId)->find();
            if ($userObj['prize_num'] <= 0) {
                throw new \Exception('您的抽奖次数已经用完');
            }

            //获取中奖商品
            $array = [];
            foreach ($goods as $index => $value) {
                $array[$value['id']] = $value['gailv'];
            }
            $winnerId = $this->getPrize($array);
            if ($winnerId === '') {
                throw new \Exception('奖品已抽完');
            }
            $winnerGoods = Db::table('shop_prize_goods')->where('id', $winnerId)->find();

            Db::startTrans();
            try {
                //减少用户抽奖次数
                $userPrizeTimes = $userObj['prize_num'] - 1;
                $userUpdateRes = Db::table('users')->where('user_id', $userId)->update(['prize_num' => $userPrizeTimes <= 0 ? 0 : $userPrizeTimes]);
                if (empty($userUpdateRes)) {
                    throw new \Exception('用户信息保存失败');
                }

                //减少商品库存
                $goodsNum = $winnerGoods['num'] - 1;
                $goodsUpdateRes = Db::table('shop_prize_goods')->where('id', $winnerId)->update(['num' => $goodsNum <= 0 ? 0 : $goodsNum]);
                if (empty($goodsUpdateRes)) {
                    throw new \Exception('商品保存失败');
                }
                //保存中奖记录
                $where['user_id'] = $this->userInfo['user_id'];
                $where['prize_id'] = $winnerId;
                $where['wintime'] = time();
                $where['bianma'] = 'A-'.date('YmdHis').'-'.$this->userInfo['user_id'];
                $where['wlstatus'] = 0;
                $where['status'] = 0;
                $where['num'] = 1;
                if($winnerGoods['isnone'] == 1){
                    $where['isnone'] = 1;
                }else{
                    $where['isnone'] = 0;
                }
                $prizewin = new PrizeWinModel();
                $savePrizewinRes = $prizewin->create($where);
                if (empty($savePrizewinRes)) {
                    throw new \Exception('中奖记录保存失败');
                }

                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                throw $e;
            }
            cache($cacheKey, null);
        } catch (\Exception $e) {
            cache($cacheKey, null);
            return $this->error($e->getMessage());
        }


        return $this->success(200, '', ['goods' => $winnerGoods, 'userTimes' => $userPrizeTimes]);
    }

    /**
     * 获取概率中随机一个
     * @param $array array 数组key=id,value=概率
     * @return int|string
     */
    public function getPrize($array = [])
    {
        $result = '';
        //概率数组的总概率精度
        $proSum = array_sum($array);
        //概率数组循环
        foreach ($array as $key => $proCur) {
            $randNum = mt_rand(1, $proSum);
            if ($randNum <= $proCur) {
                $result = $key;
                break;
            } else {
                $proSum -= $proCur;
            }
        }
        unset ($array);
        return $result;
    }


    /*
     * 判断是否开启抽奖
     */
    public function isopenPrize(){
        $prizeSetres = Db::table('shop_prize_set')->where('id',1)->find();
        if($prizeSetres['isopen'] == 0){
            //$this->error('抽奖暂未开启，请耐心等待','','0');
            $this->success("抽奖暂未开启，请耐心等待",'','0');
        }
        if($prizeSetres['isopenday'] == 1){
            $days = $prizeSetres['days'];
            $day = abs(date($days));
            //当前时间第几天
            $todayday = abs(date("d"));

            //当前时间是抽奖时间
            if($day != $todayday){
                $this->success("请你在指定每月的". $days ."号抽奖时间抽奖",'','0');
            }else{
                $this->success("200",'','ok');
            }
        }else{
            $this->success("200",'','ok');
        }
    }




}
